// pages/storeOpenDetail/storeOpenDetail.ts
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: getApp().globalData.IMG_URL,
    // 自定义导航栏的高度
    statusBarHeight: getApp().globalData.statusBarHeight,
    navBarHeight: getApp().globalData.navBarHeight,
    openType: 0, // 0扫码；1点击
    // 分页数据
    showLoading: true,
    showLoadingTxt: "努力加载中...",
    pageNo: 1,
    pageSize: 200,
    isRefresh: true,
    allPages: 0,
    // 业务部分
    userInfo: {} as any,
    storeId: "",
    bizNo: '', // 桌号、房号
    storeInfo: {} as any,
    goodsPage: [] as any, // 店内所有商品
    goodsShowPage: [] as any, // 店内展示商品
    selectedGoods: [] as any,
    // tabs
    tab0Selected: true,
    tab1Selected: false,
    hasGoods: false,
    // 操作部分
    selectedTotalPrice: 0,
    selectedOldTotalPrice: 0,
    selectedTotalNum: 0,
    showModalStatus: false,
    // 活动部分
    storeActivitiesNeedShow: false,
    storeActivitiesData: [] as any
    // [
    //   { name: '大白菜', logo: "/static/icon/icon_feedback_default.png", price: "1.99", flagPrice: "2.5" },
    //   { name: '土豆', logo: "/static/icon/icon_feedback_default.png", price: "1.99", flagPrice: "2.5" },
    //   { name: '排骨', logo: "/static/icon/icon_feedback_default.png", price: "18.5", flagPrice: "22.5" },
    //   { name: '黄辣丁', logo: "/static/icon/icon_feedback_default.png", price: "1.99", flagPrice: "2.5" },
    //   { name: '草鱼本地', logo: "/static/icon/icon_feedback_default.png", price: "1.99", flagPrice: "2.5" },
    // ]
    ,
    // 处理再来一单的数据
    orderOldGoods: [] as any,
    // 分类
    leftClsList: [] as any, // 左边类型
    filterClsKey: '0'
  },
  doBack() {
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query: any) {
    const user = wx.getStorageSync('userInfo');
    this.setData({ userInfo: JSON.parse(user) });
    if (query.storeId != null) {
      console.error('扫码进入' + JSON.stringify(query))

      // 门店号
      let storeId = query.storeId
      let bizNo = query.bizNo
      this.setData({ storeId: storeId, openType: 0, bizNo: bizNo })
      // 请求数据
      this.getStoreOpenInfo(storeId)
      this.onPullDownRefresh()
      // 加载本店活动
      this.getStroeActivitiesPage(storeId)
      // 新增进店记录
      this.addStoreBrowserLog(storeId)
    } else {
      // console.error('点击进入')
      // 点击进入
      var that = this
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('acceptDataFromOpenerPage', function (param) {
        // console.error("参数：" + JSON.stringify(param))
        let orderOldGoods = param.orderOldGoods
        if (orderOldGoods != null) {
          // console.error("商品参数：" + JSON.stringify(orderOldGoods))
          that.setData({ orderOldGoods: orderOldGoods })
        }

        let storeId = param.storeId
        that.setData({ storeId: storeId, openType: 1 })
        that.getStoreOpenInfo(that.data.storeId)
        that.onPullDownRefresh()

        // 加载本店活动
        that.getStroeActivitiesPage(storeId)
        // 新增进店记录
        that.addStoreBrowserLog(storeId)
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //切换页面时调用API
    wx.pageScrollTo({
      scrollTop: 0
    })

    try {
      const storeNeedCleanAct = wx.getStorageSync('storeNeedCleanAct')
      if (storeNeedCleanAct != null && storeNeedCleanAct == 1) {
        this.buyGoodsClearAll()
        wx.setStorage({ key: 'storeNeedCleanAct', data: 0 })
      }
    } catch (error) {
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // this.onLeftItemClick("-1")
    this.setData({ pageNo: 1, isRefresh: true })
    this.getStroeGoodsPage(this.data.pageNo, "-1")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // console.info("更多数据 onReachBottom()")
    // // 查询用户订单
    // if (this.data.allPages > this.data.pageNo) {
    //   var pageNum = this.data.pageNo + 1;
    //   this.getStroeGoodsPage(pageNum, "-1")
    //   this.setData({ pageNo: pageNum, isRefresh: false })
    // } else {
    //   console.info("没更多数据")
    // }
  },
  getStoreOpenInfo(storeId: any): void {
    var that = this
    // const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/store/client/anon/queryOpenInfoById"
    wx.request({
      url: url,
      method: 'GET',
      data: {
        id: storeId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        // 'X-Access-Token': token
      },
      success(res: any) {
        wx.stopPullDownRefresh()
        if (res.data.code == 200 && res.data.result != null) {
          // storeDesImg
          var storeInfoData = res.data.result
          if (storeInfoData != null && storeInfoData.storeDesImg != null
            && storeInfoData.storeDesImg.length > 0) {
            let storeDesImgList = storeInfoData.storeDesImg.split(",");
            storeInfoData.storeDesImg = storeDesImgList
          }
          that.setData({ storeInfo: storeInfoData })
          // console.error("storeInfo=> " + JSON.stringify(that.data.storeInfo))
          // wx.setNavigationBarTitle({ title: that.data.storeInfo.storeName })
          // console.error("baseImgUrl: " + that.data.baseImgUrl)
        } else {
          // wx.setNavigationBarTitle({ title: "门店信息" })
          console.error(JSON.stringify(res))
        }
      },
    })
  },
  // 获取门店商品
  getStroeGoodsPage(pageNum: number, saleClassifyId: string) {
    if ("-1" == saleClassifyId) {
      saleClassifyId = ""
    }
    // console.error("pageNum ==> " + pageNum)
    // console.error("saleClassifyId ==> " + saleClassifyId)
    var that = this
    const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const goodsPageForHomeUrl = preUrl + "fc/goods/client/anon/storeGoodsPage"
    wx.request({
      url: goodsPageForHomeUrl,
      method: 'GET',
      data: {
        saleClassifyId: saleClassifyId,
        storeId: that.data.storeId,
        pageNo: pageNum,
        pageSize: this.data.pageSize
      },
      header: {
        'content-type': 'application/json', // 默认值
        'X-Access-Token': token
      },
      success(res: any) {
        // console.error("商品列表res ==> " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const length = res.data.result.records.length
          if (length > 0) {// 设置展示内容
            that.setData({ hasGoods: true, tab0Selected: true, tab1Selected: false })
          } else {
            that.setData({ hasGoods: false, tab0Selected: false, tab1Selected: true })
          }

          for (let index = 0; index < length; index++) {
            const item = res.data.result.records[index]
            if (item != null) {
              const cover = item.goodsCover;
              if (cover.includes(',')) {
                const firstIndex = cover.indexOf(',');
                const coverReal = cover.substring(0, firstIndex);
                item.goodsCover = coverReal
              } else {
                item.goodsCover = cover
              }
            }
          }
          // that.setData({ goodsPage: res.data.result.records })

          if (that.data.isRefresh) {// 刷新
            that.setData({ goodsPage: res.data.result.records })
            that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
          } else {// 加载更多
            that.setData({ goodsPage: that.data.goodsPage.concat(res.data.result.records) })
            that.setData({ showLoading: false, showLoadingTxt: "努力加载中..." })
          }
          that.setData({ allPages: res.data.result.pages })

          // 处理
          const goodsPage = that.data.goodsPage
          let clsMap: Map<string, string> = new Map();
          var needOther = false // 是否填充“其他”分类

          for (let num = 0; num < goodsPage.length; num++) {
            const newGoods: any = goodsPage[num]
            // 存再一单数据（有历史订单）时，处理回填
            if (that.data.orderOldGoods != null && that.data.orderOldGoods.length > 0) {
              for (let index = 0; index < that.data.orderOldGoods.length; index++) {
                const oldGoods: any = that.data.orderOldGoods[index];
                if (newGoods.id == oldGoods.goodsId) {
                  newGoods.buyNum = oldGoods.saleNum
                }
              }
            }

            // 处理分类
            // console.error("newGoods.saleClassify ==> " + newGoods.saleClassify)
            // console.error("newGoods.saleClassify_dictText ==> " + newGoods.saleClassify_dictText)

            // 是否填充“其他”分类
            if (newGoods.saleClassify != null && newGoods.saleClassify != '') {
              clsMap.set(newGoods.saleClassify, newGoods.saleClassify_dictText);
            } else {
              needOther = true
            }
            // console.error("商品列表clsMap.szie ==> " + clsMap.size)
          }
          that.setData({ goodsPage: goodsPage })
          // console.error("商品列表res ==> " + JSON.stringify(clsMap))
          that.data.leftClsList.length = 0
          that.data.leftClsList.push({ id: '0', name: '店长推荐', selected: true })

          if (needOther) {// 需要时追加“其他”
            clsMap.set("-1", '其他');
          }
          for (let [key, value] of clsMap) {
            console.log(`${key}: ${value}`);
            that.data.leftClsList.push({ id: key, name: value, selected: false })
          }
          // console.error("leftClsList ==> " + JSON.stringify(that.data.leftClsList))
          that.setData({ leftClsList: that.data.leftClsList })

          // 设置过滤条件
          that.setData({ filterClsKey: '0' })

          // 统计
          that.doCount();
        } else {
          console.info(JSON.stringify(res))
        }
      },
    })
  },
  // 门店活动数据
  getStroeActivitiesPage(storeId: string) {
    var that = this
    const token = wx.getStorageSync('token')
    const preUrl = getApp().globalData.SERVER_URL
    const allUrl = preUrl + "fc/storeActivities/open/list"
    wx.request({
      url: allUrl,
      method: 'GET',
      data: {
        tenantId: storeId,
        pageNo: 1,
        pageSize: 200
      },
      header: {
        'content-type': 'application/json', // 默认值
        'X-Access-Token': token
      },
      success(res: any) {
        console.error("门店活动数据res ==> " + JSON.stringify(res))
        wx.stopPullDownRefresh()
        if (res.data.code == 200) {
          const length = res.data.result.records.length
          if (length > 0) {// 设置展示内容
            that.setData({ storeActivitiesNeedShow: true})

            for (let index = 0; index < length; index++) {
              const item = res.data.result.records[index]
              if (item != null) {
                const cover = item.goodsCover;
                if (cover.includes(',')) {
                  const firstIndex = cover.indexOf(',');
                  const coverReal = cover.substring(0, firstIndex);
                  item.goodsCover = coverReal
                } else {
                  item.goodsCover = cover
                }
              }
            }
            that.setData({ storeActivitiesData: res.data.result.records })
            // console.error("门店活动数据 allData ==> " + JSON.stringify(that.data))
          } else {
            that.setData({ storeActivitiesNeedShow: false})
          }
        } else {
          that.setData({ storeActivitiesNeedShow: false})
          console.info("异常："+JSON.stringify(res))
        }
      },
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  gotoGoodsDetail(param: any): void { // 打开商品详情
    wx.navigateTo({
      url: '/pages/goods/goodsDetail/goodsDetail',
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { goodsId: param.currentTarget.dataset.id })
      }
    })
  },
  doCall(param: any) {
    var phone = param.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function (res) {
        console.log('拨打电话成功！');
      },
      fail: function (res) {
        console.log('拨打电话失败！');
      }
    })
  },
  doNavi(param: any) {
    const that = this

    wx.openLocation({
      latitude: that.data.storeInfo.locLat, // 纬度，范围为-90~90，负数表示南纬
      longitude: that.data.storeInfo.locLng, // 经度，范围为-180~180，负数表示西经
      scale: 15, // 缩放比例
      name: that.data.storeInfo.storeName,
      address: that.data.storeInfo.locAddress,
      success: function (r) {
        console.log(r)
      }
    })
  },
  gotoPage(param: any): void {
    let pagePath = param.currentTarget.dataset.path
    // console.error("pagePath: " + pagePath)
    wx.navigateTo({
      url: pagePath,
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { id: "test" })
      }
    })
  },
  // 商品加购-商品列表
  buyGoodsAdd(param: any): void {
    let goods = param.currentTarget.dataset.goods
    this.goodsAdd2(goods)
  },
  // 商品减购-商品列表
  buyGoodsSub(param: any): void {
    let goods = param.currentTarget.dataset.goods
    this.goodsSub2(goods)
  },
  // 商品加购-商品列表
  buyGoodsAdd4Selected(param: any): void {
    let goods = param.currentTarget.dataset.goods
    for (let index = 0; index < this.data.goodsPage.length; index++) {
      let item = this.data.goodsPage[index]
      if (goods.id == item.id) {
        // console.error("相等 -> --------------------")
        this.goodsAdd2(goods)
      }
    }
  },
  // 商品减购-商品列表
  buyGoodsSub4Selected(param: any): void {
    let goods = param.currentTarget.dataset.goods

    for (let index = 0; index < this.data.goodsPage.length; index++) {
      let item = this.data.goodsPage[index]
      if (goods.id == item.id) {
        this.goodsSub2(goods)
      }
    }

    // 判断是否隐藏弹出框
    this.setData({ showModalStatus: this.data.selectedTotalNum > 0 })
  },
  // 商品加购-公共方法
  goodsAdd2(goods: any): void {
    // console.error("加购 goods = " + )
    let buyNum: number = goods.buyNum == undefined ? 0 : goods.buyNum

    const goodsPage = this.data.goodsPage
    for (let index = 0; index < goodsPage.length; index++) {
      const goodsItem = goodsPage[index];
      if (goodsItem.id == goods.id) {
        goodsItem.buyNum = buyNum + 1
      }
    }
    this.setData({ goodsPage: goodsPage })

    // 统计
    this.doCount();
  },
  // 商品减购-公共方法
  goodsSub2(goods: any): void {
    let buyNum: number = goods.buyNum == undefined ? 0 : goods.buyNum
    const goodsPage = this.data.goodsPage
    for (let index = 0; index < goodsPage.length; index++) {
      const goodsItem = goodsPage[index];
      if (goodsItem.id == goods.id) {
        if (buyNum > 0) {
          goodsItem.buyNum = buyNum - 1
        } else {
          goodsItem.buyNum = 0
        }
      }
    }
    this.setData({ goodsPage: goodsPage })

    // 统计
    this.doCount();
  },
  // 商品减购-清除所有
  buyGoodsClearAll(): void {
    for (let index = 0; index < this.data.goodsPage.length; index++) {
      var shoppingCarNumKey = "goodsPage[" + index + "].buyNum";
      this.setData({ [shoppingCarNumKey]: 0 })
    }
    // 统计
    this.doCount();
    // 判断是否隐藏弹出框
    this.setData({ showModalStatus: this.data.selectedTotalNum > 0 })
  },
  // 计算
  doCount() {
    var totalPrice = 0
    var totalPriceOld = 0
    var selectedNum = 0
    var selectedGoodsTemp = []

    // console.error("goodsPage = " + JSON.stringify(this.data.goodsPage))

    for (let index = 0; index < this.data.goodsPage.length; index++) {
      let goods = this.data.goodsPage[index]

      // console.error("goods.buyNum != undefined 前" + goods.buyNum)
      if (goods.buyNum != undefined && goods.buyNum != 0) {
        // console.error("goods.buyNum != undefined 中" + goods.buyNum)
        // 加入选中集合中
        selectedGoodsTemp.push(goods)

        // console.error("goods.buyNum != undefined：goods.goodsSalePrice=" + goods.goodsSalePrice)
        // 当前销售总价
        totalPrice = totalPrice + goods.buyNum * goods.goodsSalePrice

        // 原价计算  取最大值
        let flagPrice = goods.goodsFlagPrice > goods.goodsSalePrice ? goods.goodsFlagPrice : goods.goodsSalePrice
        // 原总价
        totalPriceOld = totalPriceOld + goods.buyNum * flagPrice
        // 选中数量
        selectedNum = selectedNum + goods.buyNum
      }
    }

    // console.error("doCount().totalPrice = " + totalPrice.toFixed(2))
    // 更新数据
    this.setData({
      selectedTotalPrice: new Number(totalPrice.toFixed(2)).valueOf(),
      selectedOldTotalPrice: new Number(totalPriceOld.toFixed(2)).valueOf(),
      selectedTotalNum: selectedNum,
      selectedGoods: selectedGoodsTemp
    })

    // if (selectedNum == 0) {
    //   this.hideModal()
    //   // 没选中时,取消监听返回
    //   wx.disableAlertBeforeUnload({ success: function (res) { }, fail: function (errMsg) { } })
    // } else {
    //   // 有选中时,监听返回
    //   wx.enableAlertBeforeUnload({
    //     message: "已经选择 " + selectedNum + " 份商品，确定关闭吗？", success: function (res) { }, fail: function (errMsg) { }
    //   });
    // }
    // console.error("setData = " + JSON.stringify(this.data))

    // 刷新展示商品数据
    this.doFilterGooods()
  },
  showOrderList() {
    if (this.data.selectedTotalNum == 0) {
      wx.showToast({ title: '请先选择商品', icon: 'error', duration: 2000 })
      return
    }
    this.showModal()
  },
  doSubmitOrder() {
    if (this.data.selectedTotalNum == 0) {
      wx.showToast({ title: '请先选择商品', icon: 'error', duration: 2000 })
      return
    }

    let that = this
    // console.error("提交：doSubmitOrder")
    let pagePath = "/pages/order/orderSubmite/orderSubmite"
    wx.navigateTo({
      url: pagePath,
      events: {
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据  
        res.eventChannel.emit('acceptDataFromOpenerPage', { selectedGoods: that.data.selectedGoods, storeInfo: that.data.storeInfo, bizNo: that.data.bizNo })
      }
    })
  },

  showModal: function () {// 显示遮罩层
    if (this.data.showModalStatus) {
      this.hideModal()
      return
    }
    let that = this
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    // this.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }.bind(that), 200)
  },
  hideModal() {// 隐藏遮罩层
    let that = this
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    // this.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(that), 200)
  },
  switchTab(param: any) {
    let index: String = param.currentTarget.dataset.index
    switch (index) {
      case "0":
        // console.error("switchTab data case 0")
        this.setData({ tab0Selected: true, tab1Selected: false })
        break;
      case "1":
        // console.error("switchTab data case 1")
        this.setData({ tab0Selected: false, tab1Selected: true })
        break;
      default:
        // console.error("switchTab data default")
        break;
    }
  },
  addStoreBrowserLog(storeId: string) { // 新增门店记录
    const token = wx.getStorageSync('token')
    const userId = this.data.userInfo.id
    const url = getApp().globalData.SERVER_URL + "fc/emall/browser/add"
    wx.request({
      url: url,
      method: 'POST',
      data: {
        storeId: storeId,
        tenantId: storeId,
        customerId: userId
      },
      header: {
        // 'content-type': 'application/x-www-form-urlencoded', // 默认值
        'X-Access-Token': token
      },
      success(res: any) {
        // console.error(JSON.stringify(res))
      },
    })
  },
  // 分类选择事件
  clsListClieck(param: any) {
    console.error("左边点击：" + JSON.stringify(param.currentTarget.dataset.item))
    // 设置 选中项
    const actItem = param.currentTarget.dataset.item
    var leftClsList = this.data.leftClsList;
    for (let index = 0; index < leftClsList.length; index++) {
      leftClsList[index].selected = (leftClsList[index].id === actItem.id)
    }
    this.setData({ leftClsList: leftClsList })

    // 设置 选中项
    this.setData({ filterClsKey: actItem.id })
    this.doFilterGooods()
  },
  doFilterGooods() { // 重新过滤产品
    const clsId = this.data.filterClsKey
    var goodsShowPage = null
    if (clsId == '0') {// 显示所有
      goodsShowPage = this.data.goodsPage
    } else if (clsId == '-1') {
      goodsShowPage = this.data.goodsPage.filter(item => item.saleClassify === null);
    } else {
      goodsShowPage = this.data.goodsPage.filter(item => item.saleClassify === clsId);
    }
    // console.error("doFilterGooods：" + JSON.stringify(goodsShowPage))
    this.setData({ goodsShowPage: goodsShowPage })
  },

  // 扫码下单
  doScanCode() {
    // console.error("扫码结果：doScanCode")
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        //   console.error("扫码结果：" + JSON.stringify(res))
        let path = res.path
        let pagePath: String = path.substring(0, path.indexOf("?"))
        let param: String = path.substring(path.indexOf("=") + 1)
        // console.error("扫码结果： pagePath = " + pagePath)
        // console.error("扫码结果：param = " + param)
        wx.redirectTo({ url: "/" + pagePath + '?scene=' + param })
      },
      error(res: any) {
        console.error("扫码结果：" + JSON.stringify(res))
      }
    })
    
    
    // // console.error("扫码结果：doScanCode")
    // const that = this
    // wx.scanCode({
    //   onlyFromCamera: true,
    //   success(res) {
    //     // console.error("扫码结果：" + JSON.stringify(res))
    //     let path = res.path
    //     // console.error("res.path: " + path)
    //     // let pagePath = path.substring(0, path.indexOf("?"))
    //     // // console.error("res.path: substr0 = " + pagePath)
    //     let param: String = path.substring(path.indexOf("=") + 1)
    //     // // console.error("res.path: substr1 = " + param)
    //     var paramArr: string[];
    //     if (param.includes("%")) {
    //       paramArr = param.split('%')
    //     } else {
    //       paramArr = param.split('&')
    //     }
    //     // console.error("paramArr[0]: " + paramArr[0])
    //     // console.error("paramArr[1]: " + paramArr[1])
    //     // console.error("paramArr[2]: " + paramArr[2])

    //     that.setData({ bizNo: paramArr[2] })
    //   },
    //   error(res: any) {
    //     console.error("扫码结果：" + JSON.stringify(res))
    //   }
    // })
  },
})